// ==UserScript==
// @name         小说阅读优化器
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  优化小说阅读体验，自动识别标题和正文，加载下一页内容
// @author       anuos
// @match        https://www.zuizaoxiaoshuo.com/ml/*/*.html
// @match        http://www.oread8.net/book/*/*.html
// @match        http://www.xhytd.com/*/*/*.html
// @match        https://www.xinfengwenxue.com/*/*.html
// @grant        GM_addStyle
// @grant        GM_xmlhttpRequest
// @grant        GM_setValue
// @grant        GM_getValue
// @connect      *
// ==/UserScript==

(function() {
    'use strict';

    // 常见的小说标题和正文的类名/ID
    const COMMON_TITLE_SELECTORS = [
        '.title', '.novel-title', '.book-title', '.chapter-title',
        '#title', '#novel-title', '#book-title', '#chapter-title',
        'h1', 'h2'
    ];

    const COMMON_CONTENT_SELECTORS = [
        '.content', '.novel-content', '.book-content', '.chapter-content',
        '#content', '#novel-content', '#book-content', '#chapter-content',
        '.article', '.read-content', '.chapter-text'
    ];

    const COMMON_NEXT_PAGE_SELECTORS = [
        '.next-page', '.next-chapter', '.page-next',
        '#next-page', '#next-chapter', '#page-next','#next-pager', '#pager_next',
        'a:contains("下一章")', 'a:contains("下一页")' // 替换了无效的:contains选择器
    ];

    let isLoading = false;
    let savedNextPageUrl = null;

    // 应用优化样式
    GM_addStyle(`
        .novel-reader-optimized {
            background: white !important;
            color: #4d4d4d !important;
            font-family: "Microsoft YaHei", sans-serif !important;
            margin: 0 !important;
            width: 100% !important;
            max-width: 100% !important;
            box-sizing: border-box !important;
            overflow: hidden !important;
        }

        .novel-reader-title {
            font-size: 18px !important;
/*             font-weight: bold !important; */
            text-align: left !important;
            margin-bottom: 20px !important;
        }

        .novel-reader-content {
            font-size: 14px !important;
            line-height: 26px !important;
            text-align: justify !important;
            white-space: pre-line !important;
        }

        .novel-reader-content p {
            margin: 0 0 1em 0 !important;
        }

        .novel-reader-loading {
            text-align: center;
            padding: 20px;
            color: #666;
        }
    `);

    // 查找匹配的元素
    function findElement(selectors, root = document) {
        const $root = $(root)
        for (const selector of selectors) {
            try {
              // console.log(selector)
                const element = $root.find(selector);
                if (element[0]) {
                    return element[0];
                }
            } catch (e) {
                console.warn(`Invalid selector: ${selector}`, e);
            }
        }
        return null;
    }

    // 提取纯文本内容
    function extractText(element) {
        if (!element) return '';

        // 克隆元素以避免修改原始DOM
        const clone = element.cloneNode(true);

        // 移除不需要的元素（广告、导航等）
        const unwanted = clone.querySelectorAll('div, span, script, style, iframe, noscript, button, input, form');
        unwanted.forEach(el => el.remove());

        return clone.textContent.trim();
    }

    // 获取下一页URL
    function getNextPageUrl() {
        const nextPageLink = findElement(COMMON_NEXT_PAGE_SELECTORS);
        return nextPageLink ? nextPageLink.href : null;
    }

    // 优化页面显示
    function optimizePage(titleElement, contentElement, nextPageUrl) {
        const titleText = extractText(titleElement);
        const contentText = extractText(contentElement);

        // 创建优化后的容器
        const optimizedContainer = document.createElement('div');
        optimizedContainer.className = 'novel-reader-optimized';

        // 添加标题
        const titleDiv = document.createElement('div');
        titleDiv.className = 'novel-reader-title';
        titleDiv.textContent = titleText;
        optimizedContainer.appendChild(titleDiv);

        // 添加内容
        const contentDiv = document.createElement('div');
        contentDiv.className = 'novel-reader-content';
        contentDiv.innerHTML = contentText.replace(/\n{3,}/g, '\n\n').replace(/\n/g, '<br>').replace(/[\s\n\r\t]{2,}/g, '<br>');;
        optimizedContainer.appendChild(contentDiv);

        // 替换原页面内容
        document.body.innerHTML = '';
        document.body.appendChild(optimizedContainer);

        return { contentDiv, nextPageUrl };
    }

    // 加载下一页内容
    function loadNextPage(currentContentDiv, nextPageUrl) {
        if (!nextPageUrl || isLoading) return;
        isLoading = true;

        // 添加加载指示器
        const loadingDiv = document.createElement('div');
        loadingDiv.className = 'novel-reader-loading';
        loadingDiv.textContent = '正在加载下一页...';
        currentContentDiv.parentNode.appendChild(loadingDiv);


        console.log('11111111' + nextPageUrl)
        // 请求下一页内容
        GM_xmlhttpRequest({
            method: 'GET',
            url: nextPageUrl,
            onload: function(response) {

                isLoading = false;
                const parser = new DOMParser();
                const nextPageDoc = parser.parseFromString(response.responseText, 'text/html');

                // 查找下一页的标题和内容
                const nextTitle = findElement(COMMON_TITLE_SELECTORS, nextPageDoc);
                const nextContent = findElement(COMMON_CONTENT_SELECTORS, nextPageDoc);
                const newNextPageUrl = findElement(COMMON_NEXT_PAGE_SELECTORS, nextPageDoc)?.href;

                console.log(nextPageDoc)
                console.log()
                console.log(nextContent)
                if (nextContent) {
                    console.log('移除加载指示器')
                    // 移除加载指示器
                    loadingDiv.remove();
                    console.log('添加分隔线')
                    // 添加分隔线
                    const separator = document.createElement('hr');
                    separator.style.margin = '20px 0';
                    separator.style.border = '1px dashed #ddd';
                    currentContentDiv.parentNode.appendChild(separator);

                    const nextTitleDiv = document.createElement('div');
                    nextTitleDiv.className = 'novel-reader-title';
                    nextTitleDiv.innerHTML = extractText(nextTitle);
                    currentContentDiv.parentNode.appendChild(nextTitleDiv)
                    // 添加下一页内容
                    const nextContentHtml = extractText(nextContent);
                    const nextContentDiv = document.createElement('div');
                    nextContentDiv.className = 'novel-reader-content';
                    nextContentDiv.innerHTML = nextContentHtml.replace(/\n{3,}/g, '\n\n').replace(/\n/g, '<br>').replace(/[\s\n\r\t]{2,}/g, '<br>');;
                    currentContentDiv.parentNode.appendChild(nextContentDiv);
                    console.log('更新下一页URL')
                    // 更新下一页URL
                    savedNextPageUrl = newNextPageUrl;
                } else {
                    loadingDiv.textContent = '已到达最后一页';
                    setTimeout(() => loadingDiv.remove(), 2000);
                }
            },
            onerror: function(error) {
                isLoading = false;
                loadingDiv.textContent = '加载下一页失败';
                console.error('加载下一页失败:', error);
                setTimeout(() => loadingDiv.remove(), 2000);
            }
        });
    }

    // 主函数
    function main() {
        const titleElement = findElement(COMMON_TITLE_SELECTORS);
        const contentElement = findElement(COMMON_CONTENT_SELECTORS);
        savedNextPageUrl = getNextPageUrl();

        if (titleElement && contentElement) {
            const { contentDiv } = optimizePage(titleElement, contentElement, savedNextPageUrl);

            // 监听滚动事件，仅在到达底部时加载下一页
            window.addEventListener('scroll', function() {
                const scrollPosition = window.innerHeight + window.scrollY;
                const pageHeight = document.body.offsetHeight;
                // 距离底部50px时触发加载
                if (pageHeight - scrollPosition < 50 && savedNextPageUrl && !isLoading) {
                    loadNextPage(contentDiv, savedNextPageUrl);
                }
            }, { passive: true });
        }
    }


    // 延迟执行，确保页面加载完成
    setTimeout(main, 1000);


})();